import json

import cv2
import numpy as np
import pyautogui
import config
from client.client import Client


def sendProp(client:Client):
    props = []
    print(f"sendProp: {config.labs}")
    # while config.labs:
    #     props.clear()  # 清空列表以避免重复
    #     shot = take_screenshot()  # 替换为实际的截图函数
    #     # 通过颜色判断是否是黑屏了
    #     if is_black_screen(shot):
    #         p = Prop()
    #         p.black = True
    #         props.append(p)
    #     results = yolo.predict(source=shot, verbose=False)  # 替换为实际的预测函数
    #     # 处理预测结果
    #     for result in results:
    #         for i in range(len(result)):
    #             p = Prop(get_name(result.boxes.cls[i]), result.boxes.xywh[i])
    #             props.append(p)
    #     # 创建 Mes 对象并发送
    #     # 将 props 列表中的每个 Prop 对象转换为字典，并序列化为 JSON
    #     props_dict_list = [prop.to_dict() for prop in props]
    #     message = Mes(type="prop", data=json.dumps(props_dict_list))
    #     client.send_message(message)

class Prop:
    def __init__(self, name: str, xywh: list[float]):
        self.name = name
        self.x = float(xywh[0])
        self.y = float(xywh[1])
        self.w = float(xywh[2])
        self.h = float(xywh[3])
        self.black = False

    def to_dict(self):
        return {
            "name": self.name,
            "x": self.x,
            "y": self.y,
            "w": self.w,
            "h": self.h,
            "black": self.black
        }


def get_name(n: int) -> str:
    i = int(n)
    st = config.labs[i]
    if st == None:
        print(f"key不存在={i}")
        return None
    else:
        return st


def take_screenshot():
    # 截取屏幕截图
    screenshot = pyautogui.screenshot()
    screenshot_np = np.array(screenshot)
    screenshot_bgr = cv2.cvtColor(screenshot_np, cv2.COLOR_RGB2BGR)
    return screenshot_bgr
def is_black_screen(image, threshold=10):
    # 计算图像的平均亮度
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    average_brightness = np.mean(gray_image)
    # 判断平均亮度是否低于某个阈值
    return average_brightness < threshold